﻿/*========================== 
 * @author 郑金泉
 * @desc 应用配置信息类
 * ========================= */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Obsidian.Utils;

namespace Obsidian.Config
{
    public class AppConfig
    {

        private static readonly string APP_CONFIG_FILE = RuntimeUtil.BinPath + "\\AppConfig.xml";
        private static DateTime configModified = DateTime.MinValue;
        private static XmlDocument xmlDoc = null;
        private static bool isDebug = false;

        public static DateTime Modified
        {
            get { return configModified; }
        }

        public static string FullPath(string path)
        {
            path = path.Replace("%BIN_PATH%", RuntimeUtil.BinPath);
            return path;
        }

        public static bool CheckForChanged()
        {
            FileInfo file = new FileInfo(APP_CONFIG_FILE);
            return !configModified.Equals(file.LastWriteTime);
        }

        public static bool IsDebug
        {
            get
            {
                return isDebug;
            }
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        public static XmlDocument GetXml()
        {
            try
            {
                if (xmlDoc == null || CheckForChanged())
                {
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(APP_CONFIG_FILE);
                    FileInfo file = new FileInfo(APP_CONFIG_FILE);

                    string strDebug;
                    XmlNode xmlNode = xmlDoc.SelectSingleNode("appConfig");
                    if (XmlUtil.TryGetAttrValue(xmlNode, "debug", out strDebug))
                    {
                        if (!bool.TryParse(strDebug, out isDebug))
                            isDebug = false;
                    }

                    configModified = file.LastWriteTime;
                }
                return xmlDoc;
            }
            catch (Exception ex)
            {
                throw new Exception("读取配置文件出错!");
            }
        }

    }
}
